
class SelectSort {
    static sort(l) {
        for (let i = 0; i < l.length; i++) {
            let miniIndex = i

            for (let j = i; j < l.length; j++) {
                if (l[j] < l[miniIndex]) {
                    miniIndex = j
                }
            }
            SelectSort.exchange(i, miniIndex, l)
        }
    }

    static exchange(a, b, l) {
        let temp = l[a]
        l[a] = l[b]
        l[b] = temp
    }
}

class InsertSort {
    static sort(l) {
        for (let i = 1; i < l.length; i++) {
            const a = l[i]
            let j = i

            while(j > 0 && a < l[j - 1]) {
                l[j] = l[j - 1]
                j--
            }
            l[j] = a
        }
    }
}

class MergeSort {
    static sort(arr) {
        MergeSort.sortByRecursion(arr, 0, arr.length - 1)
    }

    static sortByRecursion(arr, l, r) {
        if (l >= r) {return}

        const mid = l + Math.floor((r - l) / 2)
        MergeSort.sortByRecursion(arr, l, mid)
        MergeSort.sortByRecursion(arr, mid+1, r)
        if (arr[mid] > arr[mid + 1]) {
            MergeSort.merge(arr, l, mid, r)
        }
        
    }

    static merge(arr, l, mid, r) {
        const temp = arr.slice(l, r + 1)

        let n = l
        let i = l
        let j = mid + 1
        while(n <= r) {
            if (i > mid) {
                arr[n] = temp[j - l]
                j += 1
            }else if (j > r) {
                arr[n] = temp[i - l]
                i += 1
            }else if (temp[i - l] <= temp[j - l]) {
                arr[n] = temp[i - l]
                i += 1
            }else {
                arr[n] = temp[j - l]
                j += 1
            }
            n += 1
        }
    }
}


export {SelectSort, InsertSort, MergeSort}




